<template>
  <div class="user-center-container">
    <el-aside class="left-aside" width="250px">
      <div class="user-profile">
        <input 
          type="file" 
          ref="fileInput" 
          style="display: none" 
          accept="image/jpeg,image/png,image/gif" 
          @change="handleFileChange"
        >
        <div class="avatar-container">
          <el-avatar 
            :size="80" 
            :src="user.avatar" 
            class="user-avatar"
            @click="showAvatarPreview"
          >
            <img v-if="!user.avatar" :src="DEFAULT_AVATAR"/>
          </el-avatar>
          <div class="edit-icon" @click.stop="triggerFileInput">
            <el-icon><Camera /></el-icon>
          </div>
        </div>
        <div class="user-info">
          <div class="username">{{ user.username }}</div>
          <div class="uid">UID: <el-tag size="small">{{ user.uid }}</el-tag></div>
        </div>
      </div>

      <el-menu
        :default-active="activeMenu"
        class="side-menu"
        router
        @select="handleMenuSelect"
      >
        <el-menu-item index="/Mine/fabu">
          <el-icon><Document /></el-icon>
          <span>我发布的</span>
        </el-menu-item>
        <el-menu-item index="/Mine/maichu">
          <el-icon><SoldOut /></el-icon>
          <span>我卖出的</span>
        </el-menu-item>
        <el-menu-item index="/Mine/maidao">
          <el-icon><ShoppingCart /></el-icon>
          <span>我买到的</span>
        </el-menu-item>
        <el-menu-item index="/Mine/shoucang">
          <el-icon><Star /></el-icon>
          <span>我的收藏</span>
        </el-menu-item>
        <el-menu-item index="/Mine/Address">
          <el-icon><Location /></el-icon>
          <span>地址编辑</span>
        </el-menu-item>
        <el-menu-item index="/Mine/Settings">
          <el-icon><Setting /></el-icon>
          <span>设置</span>
        </el-menu-item>
        <el-menu-item index="/Mine/feedback">
          <el-icon><Star /></el-icon>
          <span>信用及评价</span>
        </el-menu-item>
        <el-menu-item index="/Mine">
          <el-icon><Setting /></el-icon>
          <span>待开发功能</span>
        </el-menu-item>
        <el-menu-item index="logout" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-main class="right-main">
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <component :is="Component || DefaultFeedback" />
        </transition>
      </router-view>
    </el-main>

    <el-dialog 
      v-model="avatarPreviewVisible" 
      width="90%"
      top="5vh"
      :show-close="false"
      custom-class="avatar-preview-dialog"
      :modal="false"
    >
      <div class="preview-content">
        <img 
          :src="user.avatar || DEFAULT_AVATAR" 
          class="preview-image"
          @click="avatarPreviewVisible = false"
        >
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            size="large" 
            @click="triggerFileInput"
            class="change-avatar-btn"
          >
            <el-icon><Upload /></el-icon>
            <span>更换头像</span>
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import apiClient from '@/utils/request'
import {authHandler} from '@/utils/authUtils'
import Feedback from '@/views/review/feedback.vue'
import {
  Document,
  SoldOut,
  ShoppingCart,
  Star,
  Location,
  Setting,
  SwitchButton,
  Camera,
  Upload
} from '@element-plus/icons-vue'
import {DEFAULT_AVATAR} from '@/utils/userUtils'
const user = ref({
  username: '昵称',
  uid: '123456',
  avatar: ''
})

const route = useRoute()
const router = useRouter()
const DefaultFeedback = Feedback
const fileInput = ref(null)
const avatarPreviewVisible = ref(false)

const activeMenu = computed(() => route.path)

const loadUserAvatar = () => {
  // First try to get from localStorage
  const savedUser = localStorage.getItem('user_info');
  const savedAvatar = localStorage.getItem('user_avatar');
  
  if (savedUser) {
    const userData = JSON.parse(savedUser);
    user.value = {
      username: userData.username,
      uid: userData.uid,
      avatar: savedAvatar || DEFAULT_AVATAR
    };
    
    // If no saved avatar but user has one, update it
    if (!savedAvatar && userData.avatar_url) {
      localStorage.setItem('user_avatar', userData.avatar_url);
      user.value.avatar = userData.avatar_url;
    }
  }
};

const handleMenuSelect = (index) => {
  console.log('菜单选择:', index)
}

const showAvatarPreview = () => {
  if (user.value.avatar) {
    avatarPreviewVisible.value = true
  }
}

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(file.type)) {
    ElMessage.error('只支持 JPG/PNG/GIF 格式的图片')
    return
  }

  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 2MB')
    return
  }

  try {
    const token = localStorage.getItem('access_token');
    const tokenExpire = localStorage.getItem('token_expire');
    
    // 检查token是否过期
    if (!token || (tokenExpire && Date.now() > parseInt(tokenExpire))) {
      ElMessage.warning('登录已过期，请重新登录');
      router.push('/login');
      return;
    }

    const formData = new FormData()
    formData.append('avatar', file)

    const response = await apiClient.post('/api/users/upload-avatar/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    });
    
    if (response.data?.avatar_url) {
      user.value.avatar = response.data.avatar_url
      localStorage.setItem('user_avatar', response.data.avatar_url)
      ElMessage.success('头像上传成功')
      
      // 触发全局事件
      window.dispatchEvent(new CustomEvent('avatar-updated', {
        detail: { avatarUrl: response.data.avatar_url }
      }))
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.warning('登录已过期，请重新登录');
      localStorage.clear();
      router.push('/login');
    } else {
      ElMessage.error("上传失败："+error.response.data.message);
    }
  } finally {
    event.target.value = ''
    avatarPreviewVisible.value = false
  }
}

const handleLogout = () => {
  authHandler.clearAuthInfo()
  
  // 触发全局事件
  window.dispatchEvent(new CustomEvent('login-status-changed', {
    detail: { isLoggedIn: false }
  }))
  
  router.push('/login')
}

onMounted(() => {
  const token = localStorage.getItem('access_token');
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  
  if (!token || !isLoggedIn) {
    router.push('/login');
    return;
  }

  // Check if token is expired
  const tokenExpire = localStorage.getItem('token_expire');
  if (tokenExpire && Date.now() > parseInt(tokenExpire)) {
    localStorage.clear();
    router.push('/login');
    return;
  }

  // Try to load from localStorage first
  const savedUser = localStorage.getItem('user_info');
  if (savedUser) {
    user.value = JSON.parse(savedUser);
  } else {
    // Fallback to API with proper error handling
    apiClient.get('/api/users/user-info/').then(response => {
      user.value = response.data;
      localStorage.setItem('user_info', JSON.stringify(response.data));
    }).catch(error => {
      if (error.response?.status === 401) {
        localStorage.clear();
        router.push('/login');
      }
    });
  }
  
  loadUserAvatar();
});
</script>

<style scoped>
.user-center-container {
  display: flex;
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.left-aside {
  background-color: #fff;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  position: sticky;
  top: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.user-profile {
  padding: 30px 20px 20px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 15px;
}

.user-avatar {
  border: 2px solid #e6e6e6;
  cursor: pointer;
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.05);
}

.edit-icon {
  position: absolute;
  right: -5px;
  bottom: -5px;
  background-color: #fff;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  color: var(--el-color-primary);
  cursor: pointer;
  z-index: 1;
  transition: all 0.3s;
}

.edit-icon:hover {
  background-color: var(--el-color-primary);
  color: #fff;
  transform: scale(1.1);
}

.edit-icon .el-icon {
  font-size: 16px;
}

.user-info {
  margin-bottom: 10px;
}

.username {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 5px;
  color: var(--el-text-color-primary);
}

.uid {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.side-menu {
  border-right: none;
  flex: 1;
}

.side-menu:deep(.el-menu-item) {
  height: 48px;
  line-height: 48px;
  margin: 4px 10px;
  border-radius: 4px;
}

.side-menu:deep(.el-menu-item.is-active) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.side-menu:deep(.el-menu-item:hover) {
  background-color: var(--el-color-primary-light-8);
}

.side-menu:deep(.el-icon) {
  margin-right: 8px;
  font-size: 18px;
}

.right-main {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

:deep(.avatar-preview-dialog) {
  border-radius: 8px;
  max-width: 500px;
  margin: 0 auto;
}

:deep(.avatar-preview-dialog .el-dialog__header) {
  display: none;
}

:deep(.avatar-preview-dialog .el-dialog__body) {
  padding: 0;
  background-color: rgba(0, 0, 0, 0.9);
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  cursor: pointer;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: #fff;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.change-avatar-btn {
  width: 80%;
  height: 45px;
  font-size: 16px;
}

.change-avatar-btn .el-icon {
  margin-right: 8px;
}
</style>